﻿using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace ASmile.Helpers
{
    /// <summary>
    /// rsa 加解密(.net 4.0  使用)
    /// </summary>
    //[Obsolete("之前.net 平台可用，升级到标准库后不再使用")] 
    public static class DEncryptByRSA
    {
        /// <summary>
        /// RSA产生密钥
        /// </summary>
        /// <param name="xmlKeys">输出xml私钥</param>
        /// <param name="xmlPublicKey">输出xml公钥</param>
        public static void RSAKey(out string xmlKeys, out string xmlPublicKey)
        {
            using (System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                xmlKeys = rsa.ToXmlString(true);
                xmlPublicKey = rsa.ToXmlString(false);
            }
        }

        /// <summary>
        /// rsa 加密
        /// </summary>
        /// <param name="publicKey">base64 xml公钥</param>
        /// <param name="data">明文</param>
        /// <returns>返回base64 密文</returns>
        public static string Encrypt(string publicKey, string data)
        {
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(publicKey);
                byte[] cipherbytes = rsa.Encrypt(Encoding.UTF8.GetBytes(data), false);
                return Convert.ToBase64String(cipherbytes);
            }
        }
        /// <summary>
        /// RSA解密
        /// </summary>
        /// <param name="privateKey">base64 xml私钥</param>
        /// <param name="data">base64 密文</param>
        /// <returns>返回明文</returns>
        public static string Decrypt(string privateKey, string data)
        {
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(privateKey);
                var dataBytes = Convert.FromBase64String(data);
                var deBytes = rsa.Decrypt(dataBytes, false);
                var deStr = Encoding.UTF8.GetString(deBytes);
                return deStr;
            }
        }
    }
}